package zhoug.zui.progress;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import zhoug.logging.Logger;
import zhoug.zui.R;
import zhoug.zui.ints.OnSelectedListener;
import zhoug.zui.utils.ZUIUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

/**
 * 底部有直线和原点进度的LinearLayout
 * @Author 35574
 * @Date 2020/8/19
 * @Description
 */
public class ZUILineNodeProgressLayout extends LinearLayout {
    private static final String TAG = ">>>ZUILineNodeProgressLayout";
    private static final boolean DEBUG = false;
    private int bgColor;
    private int frontColor;
    private int radius;//圆形半径
    private int lineSize;//直线尺寸
    private int textColor;
    private int textSelectColor;
    private float textSize;
    private int select = 1;//0,1,2...
    private Paint paint;
    private float lineY;

    private OnSelectedListener onSelectedListener;

    private List<View> nodes = new ArrayList<>();

    public ZUILineNodeProgressLayout(Context context) {
        this(context, null);
    }

    public ZUILineNodeProgressLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.ZUILineNodeProgressLayout_theme);
    }

    public ZUILineNodeProgressLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(LinearLayout.HORIZONTAL);
        init(context, attrs, defStyleAttr, R.style.ZUILineNodeProgressLayout_def);
    }


    private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZUILineNodeProgressLayout, defStyleAttr, defStyleRes);
        bgColor = a.getColor(R.styleable.ZUILineNodeProgressLayout_zui_backColor, Color.GRAY);
        frontColor = a.getColor(R.styleable.ZUILineNodeProgressLayout_zui_frontColor, Color.BLACK);
        textColor = a.getColor(R.styleable.ZUILineNodeProgressLayout_zui_textColor, ZUIUtils.UN_USED_COLOR);
        textSelectColor = a.getColor(R.styleable.ZUILineNodeProgressLayout_zui_textSelectColor, ZUIUtils.UN_USED_COLOR);
        textSize = a.getDimension(R.styleable.ZUILineNodeProgressLayout_zui_textSize, -1);
        lineSize = a.getDimensionPixelSize(R.styleable.ZUILineNodeProgressLayout_zui_lineSize, 5);
        radius = a.getDimensionPixelSize(R.styleable.ZUILineNodeProgressLayout_zui_radius, 10);
        select = a.getInt(R.styleable.ZUILineNodeProgressLayout_zui_selection, -1);
        a.recycle();
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL);
        if (getPaddingBottom() == 0) {
            setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), radius * 2);
        }
    }


    /**
     * 找到NodeView
     */
    private void initNodes() {
        if (nodes.size() == 0) {
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View childAt = getChildAt(i);
                ViewGroup.LayoutParams layoutParams = childAt.getLayoutParams();
                if (layoutParams instanceof LayoutParams) {
                    if (((LayoutParams) layoutParams).node) {
                        childAt.setTag(nodes.size());
                        nodes.add(childAt);
                        if(((LayoutParams) layoutParams).nodeClickable){
                            childAt.setOnClickListener(onNodeViewClickListener);
                        }
                        if (childAt instanceof TextView) {
                            ZUIUtils.setTextColor((TextView) childAt, i == select ? textSelectColor : textColor);
                            ZUIUtils.setTextSize((TextView) childAt, textSize);
                        }
                    }
                }
            }
            if (DEBUG) {
                Logger.d(TAG, "initNodes:nodes.size=" + nodes.size());
            }
        }

    }

    /**
     * NodeView单击事件
     */
    private OnClickListener onNodeViewClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                int index= (int) v.getTag();
                setSelection(index);
            } catch (Exception e) {
            }
        }
    };


    /**
     * 获取指定下标的NodeView
     *
     * @param index
     * @return
     */
    private View getNodeView(int index) {
        if (nodes.size() > 0 && index >= 0 && index < nodes.size()) {
            return nodes.get(index);
        }
        return null;
    }


    /**
     * 更新选中
     * @param select
     */
    public void setSelection(int select) {
        if (this.select != select) {
            this.select = select;
            for (int i = 0; i < nodes.size(); i++) {
                View view = nodes.get(i);
                if (view instanceof TextView) {
                    ZUIUtils.setTextColor((TextView) view, i == select ? textSelectColor : textColor);
                }
            }
            if (onSelectedListener != null) {
                onSelectedListener.onSelected(select);
            }
            invalidate();
        }
    }

    public int getSelection() {
        return select;
    }

    public int getNodeSize(){
        return nodes.size();
    }


    /**
     * 选中改变监听
     * @param onSelectedListener
     */
    public void setOnSelectedListener(OnSelectedListener onSelectedListener) {
        this.onSelectedListener = onSelectedListener;
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        lineY = h - radius;
        if (DEBUG) {
            Logger.d(TAG, "onSizeChanged:");
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        initNodes();
        if (DEBUG) {
            Logger.d(TAG, "onMeasure:");
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        drawLine(canvas);
        drawCircle(canvas);
        if (DEBUG) {
            Logger.d(TAG, "dispatchDraw:");
        }
    }

    /**
     * 画线
     *
     * @param canvas
     */
    private void drawLine(Canvas canvas) {
        //背景
        paint.setColor(bgColor);
        paint.setStrokeWidth(lineSize);
        canvas.drawLine(0, lineY, getRight(), lineY, paint);
        //前景
        paint.setColor(frontColor);
        if (select == nodes.size() - 1 && select != 0) {
            canvas.drawLine(0, lineY, getRight(), lineY, paint);
        } else {
            View nodeView = getNodeView(select);
            if (nodeView != null) {
                int point = (nodeView.getLeft() + nodeView.getRight()) / 2;
                canvas.drawLine(0, lineY, point, lineY, paint);
            }
        }
    }

    /**
     * 画圆
     *
     * @param canvas
     */
    private void drawCircle(Canvas canvas) {
        paint.setStrokeWidth(lineSize);
        for (int i = 0; i < nodes.size(); i++) {
            View selectedView = getNodeView(i);
            if (selectedView != null) {
                int left = selectedView.getLeft();
                int right = selectedView.getRight();
                int point = (right + left) >> 1;
                if (i <= select) {
                    paint.setColor(frontColor);
                } else {
                    paint.setColor(bgColor);
                }
                canvas.drawCircle(point, lineY, radius, paint);
            }
        }

    }

    /**
     * 获取默认的LayoutParams
     *
     * @return
     */
    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        if (getOrientation() == HORIZONTAL) {
            return new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        } else if (getOrientation() == VERTICAL) {
            return new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        }
        return null;
    }

    /**
     * 检查LayoutParams是否合法
     * @param p
     * @return
     */
    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof LayoutParams;
    }

    /**
     * 根据传入的lp生成自己的LayoutParams
     * @param lp
     * @return
     */
    @Override
    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
        super.generateLayoutParams(lp);
        if (lp instanceof LayoutParams) {
            return new LayoutParams((LayoutParams) lp);
        } else if (lp instanceof MarginLayoutParams) {
            return new LayoutParams((MarginLayoutParams) lp);
        }
        return new LayoutParams(lp);
    }

    /**
     * 根据xml中的属性attrs生成自己的LayoutParams
     * @param attrs
     * @return
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }

    /**
     * 自定义LayoutParams
     */
    public static class LayoutParams extends LinearLayout.LayoutParams {
        public boolean node ;
        public boolean nodeClickable ;

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ZUILineNodeProgressLayout_Layout);
            node = a.getBoolean(R.styleable.ZUILineNodeProgressLayout_Layout_layout_node, false);
            nodeClickable = a.getBoolean(R.styleable.ZUILineNodeProgressLayout_Layout_layout_nodeClickable, false);
            a.recycle();
        }

        public LayoutParams(int width, int height) {
            super(width, height);
        }

        public LayoutParams(int width, int height, float weight) {
            super(width, height, weight);
        }

        public LayoutParams(ViewGroup.LayoutParams p) {
            super(p);
        }

        public LayoutParams(MarginLayoutParams source) {
            super(source);
        }

        public LayoutParams(LayoutParams source) {
            super(source);
        }
    }

}
